package com.himore.api.web.controller.modules;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

import com.himore.api.common.constant.UserConstants;
import com.himore.api.common.core.controller.BaseController;
import com.himore.api.common.core.domain.entity.SysUser;
import com.himore.api.common.enums.WeekInfoEnum;
import com.himore.api.common.utils.*;
import com.himore.api.web.framework.config.ServerConfig;
import com.himore.api.system.service.ISysUserService;
import com.himore.api.web.enums.TaskIdEnum;
import com.himore.api.web.model.*;
import com.himore.api.web.service.*;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.himore.api.common.annotation.Log;
import com.himore.api.common.core.domain.AjaxResult;
import com.himore.api.common.enums.BusinessType;
import com.himore.api.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.himore.api.common.core.domain.AjaxResult.error;
import static com.himore.api.common.core.domain.AjaxResult.success;

import  com.qcloud.cos.*;

/**
 * 账本Controller
 * 
 * @author dongwang
 * @date 2020-12-15
 */
@Api(tags = "账单管理")
@RestController
@RequestMapping("/system/accountBook")
public class TAccountBookController extends BaseController
{
    @Autowired
    private ITAccountBookService tAccountBookService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private PushMsgSchedule pushMsgSchedule;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ITPictureService tPictureService;

    @Autowired
    private ITTaskCompleteInfoService tTaskCompleteInfoService;

    @Autowired
    private ITSysGiftsService tSysGiftsService;

    @Autowired
    private ITSysTaskService tSysTaskService;





    public static COSClient cosClient;
    public  static  COSCredentials cred;
    public static  ClientConfig clientConfig;

    //配置信息只初始化一次
    static{
        cred = new BasicCOSCredentials(UserConstants.TCLOUUD_SELECTID, UserConstants.TCLOUUD_SELECTKEY);
        Region region = new Region(UserConstants.TCLOUUD_SELECTREGION);
        clientConfig = new ClientConfig(region);

    }

    /**
     * 查询账本列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TAccountBook tAccountBook){
        startPage();
        List<TAccountBook> list = tAccountBookService.selectTAccountBookList(tAccountBook);
        return getDataTable(list);
    }

    /**
     * 查询账本列表
     */
    @GetMapping("/getListByTime")
    public TableDataInfo getListByTime(@RequestBody TimeQueryVO timeQueryVO){
        startPage();
        SysUser user =  SecurityUtils.getLoginUser().getUser();
        String[] params = timeQueryVO.getQueryTime().split("-");
        int  year =Integer.parseInt(params[0]);
        int month = Integer.parseInt(params[1]);
        Map param = new HashMap();
        if(StringUtils.isNotEmpty(year+"")){
            param.put("year",year);
        }
        if(StringUtils.isNotEmpty(month+"")){
            param.put("month",month);
        }
        param.put("userId",user.getUserId());
        List<TAccountBook> list = tAccountBookService.getListByTime(param);
        return getDataTable(list);
    }



    /**
     * 获取账本详细信息
     */
    @ApiOperation(value = "获取账本详细信息", notes = "获取账本详细信息", produces = "application/json")
    @Log(title = "获取账单详细信息", businessType = BusinessType.QUERY)
    @GetMapping(value = "/{accountId}")
    public AjaxResult getInfo(@PathVariable("accountId") Long accountId){
        SysUser currUser=SecurityUtils.getLoginUser().getUser();
        TAccountBook accountBook = tAccountBookService.selectTAccountBookById(accountId);
        if(UserConstants.OUTCOME_TYPE_FREE.equals( accountBook.getPayType())){
            //首先判断是否有请假的记录，如果当天的有请假的记录。
            Map param = new HashMap();
            param.put("userId",currUser.getUserId());
            param.put("accountTime",accountBook.getAccountTime());
            accountBook.setLast(tAccountBookService.checkIsLast(param));
        }
        return AjaxResult.success(accountBook);
    }

    /**
     * 新增账本
     */
    @ApiOperation(value = "账单数据添加", notes = "账单数据添加", produces = "application/json")
    @Log(title = "账单数据添加", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody TAccountBook tAccountBook){
        SysUser sysUser =SecurityUtils.getLoginUser().getUser();
        //判断一周内的第一笔帐是否已经完成
        TTaskCompleteInfo tTaskCompleteInfo = new TTaskCompleteInfo();
        tTaskCompleteInfo.setTaskId(TaskIdEnum.TASK_3.getValue());
        tTaskCompleteInfo.setUserId(sysUser.getUserId());
        if(!tTaskCompleteInfoService.checkIfTaskComplete(tTaskCompleteInfo)){
            TTaskCompleteInfo completeInfo = new TTaskCompleteInfo();
            completeInfo.setUserId(sysUser.getUserId());
            completeInfo.setTaskId(TaskIdEnum.TASK_3.getValue());
            completeInfo.setCreateTime(DateUtils.getNowDate());
            tTaskCompleteInfoService.insertTTaskCompleteInfo(completeInfo);
            TSysTask sysTask = tSysTaskService.selectTSysTaskById(TaskIdEnum.TASK_3.getValue());
            //个人积分需要增加相应的积分
            SysUser user = new SysUser();
            user.setUserId(sysUser.getUserId());
            user.setScore(sysTask.getAmount());
            userService.updateScoreOrDrawInfo(user);
        }

        tAccountBook.setUserId(sysUser.getUserId());
        tAccountBook.setCreateTime(new Date());
        //当为qingerr
        if( ( null != tAccountBook.getIsIncome()  && 0==tAccountBook.getIsIncome()) &&  (UserConstants.OUTCOME_TYPE_FREE.equals(tAccountBook.getPayType())) && null !=tAccountBook.getFreeDays()) {
            for(int i=0;i<tAccountBook.getFreeDays();i++){
                Date date = tAccountBook.getAccountTime();
                if(i>0){
                    date = DateUtils.addTimeTodate(date,i);
                }
                Map param = new HashMap();
                param.put("userId",sysUser.getUserId());
                param.put("accountTime",date);
                if(tAccountBookService.checkLeaveExists(param)){
                    return  error(ErrorCodeUtil.E_228,"您在 "+DateUtils.formatDateInfo(date)+" 这一天已经存在请假记录，不允许再次请假！");
                }

            }
        }

        if(null!= tAccountBook.getPicPath()){
            File file = new File(tAccountBook.getPicPath());
            boolean isExists = file.exists();
            System.out.println("isExists ====="+isExists);
        }
            return toAjax(tAccountBookService.insertTAccountBook(tAccountBook));
    }

    /**
     * 修改账本
     */
    @ApiOperation(value = "账单数据编辑", notes = "账单数据编辑", produces = "application/json")
    @Log(title = "账单数据编辑", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResult edit(@RequestBody TAccountBook tAccountBook){
        try {
            SysUser sysUser =SecurityUtils.getLoginUser().getUser();
            if( ( null != tAccountBook.getIsIncome()  && 0==tAccountBook.getIsIncome()) &&  (UserConstants.OUTCOME_TYPE_FREE.equals(tAccountBook.getPayType())) && null !=tAccountBook.getFreeDays()) {
                for(int i=0;i<tAccountBook.getFreeDays();i++){
                    Date date = tAccountBook.getAccountTime();
                    if(i>0){
                        date = DateUtils.addTimeTodate(date,i);
                    }
                    Map param = new HashMap();
                    param.put("userId",sysUser.getUserId());
                    param.put("accountTime",date);
                    if(tAccountBookService.checkLeaveExists(param)){
                        return  error(ErrorCodeUtil.E_228,"您在 "+DateUtils.formatDateInfo(date)+" 这一天已经存在请假记录，不允许再次请假！");
                    }

                }
                Long[] ids = new Long[]{tAccountBook.getAccountId()};
                tAccountBookService.deleteTAccountBookByIds(ids);
                tAccountBookService.insertTAccountBook(tAccountBook);
                return success();
            }else{
                return toAjax(tAccountBookService.updateTAccountBook(tAccountBook));
            }
        }catch (Exception e){
            e.printStackTrace();
            return error("修改账本信息异常，请联系管理员！");
        }
    }

    /**
     * 删除账本
     */
    @ApiOperation(value = "账账单数据删除", notes = "账账单数据删除", produces = "application/json")
    @Log(title = "账账单数据删除", businessType = BusinessType.DELETE)
	@PostMapping("/remove/{accountIds}")
    public AjaxResult remove(@PathVariable Long[] accountIds){
        try {
            return toAjax(tAccountBookService.deleteTAccountBookByIds(accountIds));
        }catch (Exception e){
            e.printStackTrace();
            return error("删除账本信息异常，请联系管理员！");
        }
    }


    /**
     * 查询我的汇总信息
     */
    @ApiOperation(value = "查询我的汇总信息", notes = "查询我的汇总信息", produces = "application/json")
    @Log(title = "查询我的汇总信息", businessType = BusinessType.QUERY)
    @GetMapping("/getMytotalInfo")
    public AjaxResult getMytotalInfo() {
        Map  result = new HashMap();
        try {
            SysUser user =  SecurityUtils.getLoginUser().getUser();
            Map param = new HashMap();
            SysUser currentUser = userService.selectUserById(user.getUserId());
            if(null != currentUser){

                param.put("userId",user.getUserId());
                TotalInfoVO totalInfoVO = tAccountBookService.getMytotalInfo(param);
                int status ;
                if(null== currentUser.getNeedService() ||  StringUtils.isBlank(currentUser.getNeedService()) ){
                    status = 0;
                }else{
                    status = Integer.parseInt(currentUser.getNeedService());
                }
                totalInfoVO.setStatus(status);
                totalInfoVO.setAddress(null== currentUser.getAddress() ? "": currentUser.getAddress() );
                totalInfoVO.setCompany(null == currentUser.getCompany() ? "" :currentUser.getCompany());
                totalInfoVO.setPhoneNum(null == currentUser.getPhonenumber() ? "" :currentUser.getPhonenumber());
                totalInfoVO.setUserName(null == currentUser.getRealName()? "": currentUser.getRealName());
                String accountPrice = "null" .equals(currentUser.getAccountPrice()+"") ? "1" :currentUser.getAccountPrice()+"";
                totalInfoVO.setAccountPrice(accountPrice);
                totalInfoVO.setCarNum(null== currentUser.getCarNum() ? "": currentUser.getCarNum() );
                String basePay = ("null" .equals(currentUser.getBasePay()+"") && new BigDecimal(0.00) != currentUser.getBasePay())   ? "" :currentUser.getBasePay()+"";
                totalInfoVO.setBasePay(basePay);
                totalInfoVO.setScore(null==currentUser.getScore() ?"0":currentUser.getScore()+"");
                totalInfoVO.setUserIdentifNum(currentUser.getUserIdentifNum());
                result.put("totalInfo",totalInfoVO);
            }else{
                TotalInfoVO totalInfoVO = new TotalInfoVO();
                totalInfoVO.setTotalAmount("0.00");
                totalInfoVO.setTotalNum(0);
                totalInfoVO.setTotalDays(0);
                totalInfoVO.setContinutyDays(0);
                totalInfoVO.setStatus(0);
                totalInfoVO.setAccountPrice("1");
                totalInfoVO.setCarNum("");
                totalInfoVO.setBasePay("");
                totalInfoVO.setScore("0");
                totalInfoVO.setUserIdentifNum("");
                result.put("totalInfo",totalInfoVO);
            }
            return success(result);
        }catch (Exception e){
            e.printStackTrace();
            return error("查询我的汇总信息异常，请联系管理员！");
        }
    }

    /**
     * 根据月年查询上半年的账单信息
     */
    @Log(title = "根据月年查询上半年的账单信息", businessType = BusinessType.QUERY)
    @GetMapping("/getRecentMonthResult")
    public AjaxResult getRecentMonthResult(@RequestParam  String  queryTime) {


        //返回的每个月的信息
        ArrayList<RecentMonthResultVO>  list = new ArrayList<>();
        if(StringUtils.isBlank(queryTime)){
            return error(ErrorCodeUtil.E_101,"您输入的日期为空，请重新输入！");
        }
        //定义每个月的模板
        int yearParam = Integer.valueOf(queryTime.split("-")[0]);
        LocalDate today = LocalDate.now() ;//获取当前日期 年月日
        int currMonth = today.getMonth().getValue();
        int currYear = today.getYear();
        int  startMonth = 0;
        if(currYear  == yearParam){
            startMonth =currMonth;
            for(int  i=1;i<=startMonth;i++){
                list.add(new RecentMonthResultVO(i,0.00,0.00,0.00));
            }
        }
        if(currYear  > yearParam){
            startMonth =12;
            for(int  i=1;i<=startMonth;i++){
                list.add(new RecentMonthResultVO(i,0.00,0.00,0.00));
            }
        }
        Map  result = new HashMap();
        BigDecimal yearSalary =new BigDecimal(0);
        Map param = new HashMap();
        SysUser user =  SecurityUtils.getLoginUser().getUser();
        try {
            String[] params = queryTime.split("-");
            int  year;
            int month;
            if(params.length>0){
                year =Integer.parseInt(params[0]);
                param.put("year",year);
                if(params.length>1){
                    month = Integer.parseInt(params[1]);
                    param.put("month",month);
                }
            }else{
                return error(ErrorCodeUtil.E_101,"您输入的日期为空，请重新输入！");
            }
            param.put("userId",user.getUserId());
            List<RecentMonthResultVO> resulist= tAccountBookService.getRecentMonthResult(param);
       /*     if(null != list && list.size()>0){
                //计算每月总工资
                for(RecentMonthResultVO vo:list){
                    //double salary = (vo.getTotalAmount() >user.getBeginningAmount() ?(vo.getTotalAmount()-user.getBeginningAmount())* user.getAccountPrice() +user.getBasePay(): user.getBasePay());
                    //vo.setTotalSalary(new BigDecimal(salary));
                    yearSalary =yearSalary.add(vo.getTotalSalary());
                }
            }*/
           if(null!= resulist && resulist.size()>0){
               for (RecentMonthResultVO vo :resulist){
                   for(int j =0;j< list.size();j++) {
                       RecentMonthResultVO tem=  list.get(j);
                       if (vo.getMonth() == tem.getMonth()) {
                           change(list, j, tem, vo);
                       }
                   }
               }
           }
            result.put("list",list);
        }catch (Exception e){
            e.printStackTrace();
            return error("查询我月账单信息异常，请联系管理员！");
        }
        try {
            YearCountVO vo = tAccountBookService.getYearCountResult(param);
            if(StringUtils.isNotNull(vo)){
                result.put("yearSalary",(null== vo.getYearSalary() ? "0.00":vo.getYearSalary()+""));
                result.put("yearAmount",(null== vo.getYearAmount() ? "0.00" :vo.getYearAmount()+""));
                result.put("totalOutcome",(null== vo.getTotalOutcome() ? "0.00" : vo.getTotalOutcome()+""));
            }else{
                result.put("yearSalary","0.00");
                result.put("yearAmount","0.00");
                result.put("totalOutcome","0.00");
            }
            //result.put("totalShiftCounts",vo.getTotalShiftCounts());
            return success(result);
        }catch (Exception e){
            e.printStackTrace();
            return error("查询我年度汇总信息异常，请联系管理员！");
        }

    }
    /**
     * 修改计算工资的参数
     */
    @Log(title = "查询计算工资的参数", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/getSalaryInfo")
    public AjaxResult getSalaryInfo() {
        try {

            SysUser currUser = SecurityUtils.getLoginUser().getUser();
            SalaryInfoVO vo= new SalaryInfoVO();
            return toAjax(userService.updateUser(currUser));
        }catch (Exception e){
            e.printStackTrace();
            return error("修改计算工资的参数异常，请联系管理员！");
        }
    }


    /**
     * 修改计算工资的参数
     */
    @Log(title = "修改我的信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editSalaryInfo")
    public AjaxResult updateSalaryInfo(@RequestBody SalaryInfoVO salaryInfoVO) {
        try {
            SysUser currUser = SecurityUtils.getLoginUser().getUser();
            SysUser sysUser =userService.selectUserById(currUser.getUserId());
            TSysTask sysTask = tSysTaskService.selectTSysTaskById(TaskIdEnum.TASK_2.getValue());
            if(StringUtils.isNotBlank(salaryInfoVO.getPhoneNum())){
                SysUser user = new SysUser();
                user.setUserId(sysUser.getUserId());
                user.setPhonenumber(salaryInfoVO.getPhoneNum());
                int count = userService.checkPhoneNumIsUnic(user);
                if(count>0){
                    return error(ErrorCodeUtil.E_220,"您输入的手机号在系统中已经存在，请重新输入！");
                }
            }

            //编辑我的信息的时候，如果我的手机号是空的 ，那么就认为我的认证信息是未完成，此次的完成认证信息就是完成该任务的操作
            if(StringUtils.isNotBlank(salaryInfoVO.getPhoneNum())){
                TTaskCompleteInfo tTaskCompleteInfo = new TTaskCompleteInfo();
                tTaskCompleteInfo.setTaskId(TaskIdEnum.TASK_2.getValue());
                tTaskCompleteInfo.setUserId(sysUser.getUserId());
                if(!tTaskCompleteInfoService.checkIfTaskComplete(tTaskCompleteInfo)){
                    tTaskCompleteInfo.setCreateTime(DateUtils.getNowDate());
                    tTaskCompleteInfoService.insertTTaskCompleteInfo(tTaskCompleteInfo);
                    //个人积分需要增加相应的积分
                    SysUser user = new SysUser();
                    user.setUserId(sysUser.getUserId());
                    user.setScore(sysTask.getAmount());
                    userService.updateScoreOrDrawInfo(user);
                }

            }
            SysUser user= new SysUser();
            user.setUserId(currUser.getUserId());
            user.setBeginningAmount( !"null".equals(salaryInfoVO.getBeginningAmount()+"")?salaryInfoVO.getBeginningAmount() :0);
            user.setBasePay( !"null".equals(salaryInfoVO.getBasePay()+"")? new BigDecimal(salaryInfoVO.getBasePay()) :null);
            user.setCompany(salaryInfoVO.getCompany());
            user.setRealName(salaryInfoVO.getUserName());
            user.setAddress(salaryInfoVO.getAddress());
            user.setPhonenumber(salaryInfoVO.getPhoneNum());
            user.setAccountPrice(salaryInfoVO.getAccountPrice());
            user.setCarNum(salaryInfoVO.getCarNum());
            userService.updateUserBaseIfo(user);
            //首先判断是否有请假的记录，如果当天的有请假的记录。
            Map param = new HashMap();
            param.put("userId",currUser.getUserId());
            param.put("accountTime",DateUtils.getStandarDate());
            if(null!= salaryInfoVO.getBasePay() && !tAccountBookService.checkSalaryExists(param)){
               /* //先删除当天的工资数据
                TAccountBook accountBook = new TAccountBook();
                accountBook.setUserId(currUser.getUserId());
                accountBook.setAccountTime(DateUtils.getStandarDate());
                accountBook.setIsIncome(1);
                accountBook.setIncomeType("2");
                tAccountBookService.deleteTAccountBookByParam(accountBook);*/
                //添加一条工资的数据，
                int days =LocalDate.now().withMonth(LocalDate.now().getMonthValue()).lengthOfMonth();
                TAccountBook tAccountBook = new TAccountBook();
                tAccountBook.setIncomeType("2");
                tAccountBook.setIsIncome(1);
                tAccountBook.setInputSum(salaryInfoVO.getBasePay().doubleValue()/days);
                tAccountBook.setAccountTime(DateUtils.getStandarDate());
                tAccountBook.setUserId(currUser.getUserId());
                tAccountBook.setIncomeTypeName("工资");
                tAccountBookService.insertTAccountBook(tAccountBook);
            }
            return success();
        }catch (Exception e){
            e.printStackTrace();
            return error("修改计算工资的参数异常，请联系管理员！");
        }
    }
    /**
     * 根据月
     */
    @Log(title = "查询每天的账单详情", businessType = BusinessType.UPDATE)
    @GetMapping("/getDayInfoByTime")
    public AjaxResult getDayInfoByTime(@RequestParam  String  queryTime) {
        try {
            if(StringUtils.isBlank(queryTime)){
                return error("日期不能为空，请重新输入！");
            }
            startPage();
            SysUser user =  SecurityUtils.getLoginUser().getUser();
            String[] params = queryTime.split("-");
            int  year =Integer.parseInt(params[0]);
            int month = Integer.parseInt(params[1]);
            Map param = new HashMap();
            if(StringUtils.isNotEmpty(year+"")){
                param.put("year",year);
            }
            if(StringUtils.isNotEmpty(month+"")){
                param.put("month",month);
            }
            param.put("userId",user.getUserId());
            List<DayInfoResultVO> list = tAccountBookService.getDayInfoByTime(param);

            TAccountBook book = new TAccountBook();
            book.setUserId(user.getUserId());

            List<DayDetailVO> dayDetailVOList = tAccountBookService.selectTDayInfoList(param);
            List<HasPicVO>  hasPicVOS = tPictureService.checkIfHasPic(param);

            for(DayInfoResultVO vo :list){
                vo= transferWeekInfo(vo);
                List<DayDetailVO> detailList = new ArrayList<>();
                for(DayDetailVO dayDetailVO: dayDetailVOList){
                    if(dayDetailVO.getDay() .equals(vo.getDateValue())){
                        detailList.add(dayDetailVO);
                    }
                }
                vo.setAccountBooks(detailList);
                if(null != hasPicVOS && hasPicVOS.size()>0){
                    for(HasPicVO picVO :hasPicVOS){
                        if( picVO.getDateValue() .equals(vo.getDateValue())){
                            if( picVO.getCount()>0){
                                vo.setHasPic(true);
                            }else{
                                vo.setHasPic(false);
                            }
                        }else{
                            vo.setHasPic(false);
                        }
                    }
                }else{
                    vo.setHasPic(false);
                }
            }
            if(null != hasPicVOS && hasPicVOS.size()>0){
                boolean flag =false;
                for(HasPicVO picVO :hasPicVOS) {
                    if(checkIfExistsBookInfo(list,picVO.getDateValue())){
                        DayInfoResultVO dayInfoResultVO = new DayInfoResultVO();
                        dayInfoResultVO.setDateValue(picVO.getDateValue());
                        dayInfoResultVO.setAccountBooks(new ArrayList<>());
                        dayInfoResultVO.setHasPic(true);
                        dayInfoResultVO.setFullDate(picVO.getFullDate());
                        dayInfoResultVO.setWeek(picVO.getWeek());
                        dayInfoResultVO=transferWeekInfo(dayInfoResultVO);
                        list.add(dayInfoResultVO);
                    }
                }
            }

            Collections.sort(list,new MyComparator());

            RecentMonthResultVO  monthInfo = new  RecentMonthResultVO();
            List<RecentMonthResultVO>  tempList= tAccountBookService.getMonthResult(param);
            if(StringUtils.isNotNull(tempList) && tempList.size()>0){
                monthInfo= tempList.get(0);
            }
            Map  result = new HashMap();
            result.put("month",monthInfo.getMonth());
            result.put("monthAmount",(null== monthInfo.getTotalAmount() ? "0.00":monthInfo.getTotalAmount()+""));
            result.put("monthSalary",(null== monthInfo.getTotalSalary() ? "0.00":monthInfo.getTotalSalary()+""));
            result.put("monthOutcome", (null== monthInfo.getTotalOutcome() ? "0.00":monthInfo.getTotalOutcome()+""));
            result.put("dayData",list);
            SysUser currUser =userService.selectUserById(user.getUserId());
            result.put("basePay",currUser.getBasePay());

            return success(result);
        }catch (Exception e){
            e.printStackTrace();
            return error("查询每天的账单数据异常，请联系管理员！");
        }
    }

    public  DayInfoResultVO transferWeekInfo(DayInfoResultVO vo){
        if(WeekInfoEnum.SUN.getValue().equals(vo.getWeek())){
            vo.setWeek(WeekInfoEnum.SUN.getName());
            return vo;
        }
        if(WeekInfoEnum.MON.getValue().equals(vo.getWeek())){
            vo.setWeek(WeekInfoEnum.MON.getName());
            return vo;
        }
        if(WeekInfoEnum.TUE.getValue().equals(vo.getWeek())){
            vo.setWeek(WeekInfoEnum.TUE.getName());
            return vo;
        }
        if(WeekInfoEnum.WED.getValue().equals(vo.getWeek())){
            vo.setWeek(WeekInfoEnum.WED.getName());
            return vo;
        }
        if(WeekInfoEnum.THU.getValue().equals(vo.getWeek())){
            vo.setWeek(WeekInfoEnum.THU.getName());
            return vo;
        }
        if(WeekInfoEnum.FRI.getValue().equals(vo.getWeek())){
            vo.setWeek(WeekInfoEnum.FRI.getName());
            return vo;
        }
        if(WeekInfoEnum.SAT.getValue().equals(vo.getWeek())){
            vo.setWeek(WeekInfoEnum.SAT.getName());
            return vo;
        }else{
            return vo;
        }
    }

    public static ArrayList<RecentMonthResultVO> change(ArrayList<RecentMonthResultVO> list, int index,RecentMonthResultVO str1, RecentMonthResultVO str2) {
        int i = index;
        boolean remove = list.remove(str1);
        list.add(i,str2);
        return list;
    }


    /**
     *
     */
    @Log(title = "修改推送状态信息", businessType = BusinessType.DELETE)
    @PostMapping("/changePushStatus/{status}")
    public AjaxResult changestatus(@PathVariable String status){
        try {
            // 参数 0  关闭  1  开启
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            SysUser user = new SysUser();
            user.setUserId(sysUser.getUserId());
            user.setNeedService(status);
            userService.updateUser(user);
            return success();
        }catch (Exception e){
            e.printStackTrace();
            return error("修改推送状态信息异常，请联系管理员！");
        }
    }


    /**
     *
     */
    @Log(title = "销假", businessType = BusinessType.DELETE)
    @PostMapping("/rollbackleave")
    public AjaxResult rollbackleaveByParam(@RequestBody RollBackLeaveVO rollBackLeaveVO){
        try {
            // 参数 0  关闭  1  开启
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            TAccountBook  accountBook  = tAccountBookService.selectTAccountBookById(rollBackLeaveVO.getAccountId());
            if(StringUtils.isNull(accountBook)){
                return error(ErrorCodeUtil.E_220,"您输入的账单信息不存在！");
            }
            if("0".equals(rollBackLeaveVO.getAfter())){
                tAccountBookService.deleteTAccountBookById(rollBackLeaveVO.getAccountId());
                return success();
            }
            Date accountTime = accountBook.getAccountTime();
            Map param = new HashMap();
            param.put("after",rollBackLeaveVO.getAfter());
            param.put("accountTime",accountTime);
            param.put("userId",sysUser.getUserId());
            tAccountBookService.rollbackleaveByParam(param);
            return success();
        }catch (Exception e){
            e.printStackTrace();
            return error("修改推送状态信息异常，请联系管理员！");
        }
    }




    public  String uploadToCos(File file, long userId ){
        // 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
        // 指定要上传的文件
        String fileName = file.getName();
        String suffixName =fileName.substring(fileName.indexOf("."));
        fileName= "123"+fileName;

        // 指定要上传到 COS 上对象键
        String key = CommonUtils.generatePicKey(userId,suffixName);
        PutObjectRequest putObjectRequest = new PutObjectRequest(UserConstants.TCLOUUD_BUCKET_NAME, key, file);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        System.out.println(putObjectResult.toString());
        cosClient.shutdown();
        String  fileRealPath = UserConstants.TCLOUUD_FILE_PREFFIX+key;
        return  fileRealPath;

    }

    public static File multipartFileToFile( MultipartFile file ) throws Exception {
        File toFile = null;
        if(file.equals("")||file.getSize()<=0){
            file = null;
        }else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean checkIfExistsBookInfo(List<DayInfoResultVO> picVOList,String dayValue){
        boolean resFlag = false;
        boolean flag = true;
        HasPicVO v= new HasPicVO();
        for(DayInfoResultVO vo: picVOList){
            if(vo.getDateValue().equals(dayValue)){
                flag =false;
                break;
            }
        }
        return flag;
    }

    class MyComparator implements Comparator {

        @Override
        public int compare(Object o1, Object o2) {
            try {
                DayInfoResultVO vo1= (DayInfoResultVO)o1;
                DayInfoResultVO vo2= (DayInfoResultVO)o2;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                Date date1 = sdf.parse(vo1.getFullDate());
                Date date2 = sdf.parse(vo2.getFullDate());
                if (date2.getTime() >date1.getTime()) {
                    return 1;
                } else {
                    return -1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    }


}
